/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.live.multishop.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.enums.LiveInterfaceType;
import com.yami.shop.bean.enums.LiveProdStatusType;
import com.yami.shop.bean.model.Product;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.util.CharUtil;
import com.yami.shop.live.comment.model.LiveProdStore;
import com.yami.shop.live.comment.model.LiveRoomProd;
import com.yami.shop.live.comment.param.LiveUsableNumParam;
import com.yami.shop.live.comment.service.LiveLogService;
import com.yami.shop.live.comment.service.LiveProdStoreService;
import com.yami.shop.common.annotation.SysLog;

import javax.validation.Valid;

import com.yami.shop.live.comment.service.LiveRoomProdService;
import com.yami.shop.live.comment.util.WxImageUtil;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.ProductService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import lombok.AllArgsConstructor;
import com.yami.shop.common.util.PageParam;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 *
 *
 * @author LGH
 * @date 2020-08-04 16:57:17
 */
@RestController
@AllArgsConstructor
@RequestMapping("/live/liveProdStore" )
public class LiveProdStoreController {

    private final LiveProdStoreService liveProdStoreService;
    private final LiveLogService liveLogService;
    private final ProductService productService;
    private final WxImageUtil wxImageUtil;
    private final LiveRoomProdService liveRoomProdService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param liveProdStore
     * @return 分页数据
     */
    @GetMapping("/page" )
    public ResponseEntity<IPage<LiveProdStore>> getLiveProdStorePage(PageParam<LiveProdStore> page, LiveProdStore liveProdStore) {
        liveProdStore.setShopId(SecurityUtils.getShopUser().getShopId());
        IPage<LiveProdStore> resPage = liveProdStoreService.getPage(page, liveProdStore);
        return ResponseEntity.ok(resPage);
    }


    /**
     * 通过id查询
     * @param liveProdStoreId id
     * @return 单个数据
     */
    @GetMapping("/info/{liveProdStoreId}" )
    public ResponseEntity<LiveProdStore> getById(@PathVariable("liveProdStoreId") Long liveProdStoreId) {
        LiveProdStore liveProdStore = liveProdStoreService.getById(liveProdStoreId);
        if (Objects.nonNull(liveProdStore.getProdId())) {
            Product product = productService.getProductByProdId(liveProdStore.getProdId(), I18nMessage.getDbLang());
            if (product !=null) {
                liveProdStore.setPic(product.getPic());
                liveProdStore.setProdName(product.getProdName());
                liveProdStore.setOriProdType(product.getProdType());
            }
        }
        return ResponseEntity.ok(liveProdStore);
    }

    /**
     * 新增
     * @param liveProdStore 新增信息
     * @return 是否新增成功
     */
    @SysLog("新增" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('live:liveProdStore:save')")
    public ResponseEntity<Boolean> save(@RequestBody @Valid LiveProdStore liveProdStore) {
        if(CharUtil.length(liveProdStore.getName()) < 6 || CharUtil.length(liveProdStore.getName()) > 28){
            // 名称长度非法,最少3个汉字或者6个字符、最大14个汉字！
            throw new YamiShopBindException("yami.live.prod.name.check");
        }
        if(StrUtil.isBlank(liveProdStore.getUrl())){
            // 请选择商品！
            throw new YamiShopBindException("yami.score.select.num");
        }
        liveProdStore.setShopId(SecurityUtils.getShopUser().getShopId());
        Date date = new Date();
        liveProdStore.setCreateTime(date);
        liveProdStore.setStatus(LiveProdStatusType.NO_EXAMINE.value());
        liveProdStore.setUpdateTime(date);
        liveProdStore.setVerifyTime(null);
        return ResponseEntity.ok(liveProdStoreService.save(liveProdStore));
    }



    /**
     * 修改
     * @param liveProdStore 修改信息
     * @return 是否修改成功
     */
    @SysLog("修改" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('live:liveProdStore:update')")
    public ResponseEntity<Boolean> updateById(@RequestBody @Valid LiveProdStore liveProdStore) throws WxErrorException{
        if(CharUtil.length(liveProdStore.getName()) < 6 || CharUtil.length(liveProdStore.getName()) > 28){
            throw new YamiShopBindException("yami.live.prod.name.check");
        }
        if(!Objects.equals(liveProdStore.getShopId(), SecurityUtils.getShopUser().getShopId())) {
            // 没有权限进行操作
            throw new YamiShopBindException("yami.no.auth");
        }
        liveProdStore.setUpdateTime(new Date());
        liveProdStoreService.updateWxLiveProdById(liveProdStore);
        return ResponseEntity.ok().build();
    }

    /**
     * 提交审核
     */
    @PutMapping("/submitVerify")
    @PreAuthorize("@pms.hasPermission('live:liveProdStore:submitVerify')")
    public ResponseEntity<Boolean> submitVerify(@RequestBody LiveProdStore liveProdStore) {
        liveProdStore = liveProdStoreService.getById(liveProdStore.getLiveProdStoreId());
        if(!Objects.equals(liveProdStore.getShopId(), SecurityUtils.getShopUser().getShopId())) {
            // 没有权限进行操作
            throw new YamiShopBindException("yami.no.auth");
        }
        if (Objects.equals(LiveProdStatusType.EXAMINING.value(),liveProdStore.getStatus())) {
            // 已提交审核
            throw new YamiShopBindException("yami.submitted.examine");
        }
        boolean b = liveProdStoreService.submitVerify(liveProdStore);
        return ResponseEntity.ok(b);
    }

    /**
     * 通过id删除
     * @param liveProdStoreId id
     * @return 是否删除成功
     */
    @SysLog("删除" )
    @DeleteMapping("/{liveProdStoreId}" )
    @PreAuthorize("@pms.hasPermission('live:liveProdStore:delete')")
    public ResponseEntity<Boolean> removeById(@PathVariable Long liveProdStoreId) throws WxErrorException {
        LiveProdStore prodStore = liveProdStoreService.getById(liveProdStoreId);
        if(!Objects.equals(prodStore.getShopId(), SecurityUtils.getShopUser().getShopId())) {
            // 没有权限进行操作
            throw new YamiShopBindException("yami.no.auth");
        }
        liveProdStoreService.removeWxLiveProdById(liveProdStoreId, SecurityUtils.getShopUser().getShopId());
        return ResponseEntity.ok().build();
    }

    /**
     * 获取微信入库的商品列表
     * 商品状态，0：未审核。1：审核中，2：审核通过，3：审核驳回
     * @return 单个数据
     */
    @GetMapping("/listAppleProds" )
    public ResponseEntity<IPage<LiveProdStore>> listAppleProds(PageParam<LiveProdStore> page, Integer status,String name,Integer id) {
        if(Objects.isNull(status)){
            status = 2;
        }
        LiveProdStore liveProdStore = new LiveProdStore();
        liveProdStore.setStatus(status);
        liveProdStore.setName(name);
        liveProdStore.setShopId(SecurityUtils.getShopUser().getShopId());
        IPage<LiveProdStore> resPage = liveProdStoreService.getPage(page, liveProdStore);
        // 筛选掉已经选择的商品
        List<LiveRoomProd> prodList = liveRoomProdService.list(new LambdaQueryWrapper<LiveRoomProd>().eq(LiveRoomProd::getRoomId, id));
        List<LiveProdStore> liveProdStores = resPage.getRecords();
        // 筛选出没有分配班级的学生
        List<LiveProdStore> filterProdStores = liveProdStores.stream().filter(student -> prodList.stream().noneMatch(
                            stuClass -> stuClass.getProdStoreId().equals(student.getLiveProdStoreId()))).collect(Collectors.toList());
        resPage.setRecords(filterProdStores);
        return ResponseEntity.ok(resPage);
    }

    /**
     * 根据直播间id获取直播间已经选择的商品
     * @return 单个数据
     */
    @GetMapping("/pageProdsByRoomId")
    public ResponseEntity<IPage<LiveProdStore>> pageProdsByRoomId(PageParam<LiveProdStore> page,Integer id) {
        IPage<LiveProdStore> resPage = liveProdStoreService.pageProdByRoomId(page, id);
        return ResponseEntity.ok(resPage);
    }


    /**
     * 查询商家今日剩余可用添加直播商品、可删除商品库商品次数
     */
    @GetMapping("/getAddProdNum" )
    public ResponseEntity<LiveUsableNumParam> getAddRoomNum() {
        LiveUsableNumParam liveNum = liveLogService.getLiveNum(SecurityUtils.getShopUser().getShopId(), LiveInterfaceType.ADD_PROD_AUDIT);
        LiveUsableNumParam deleteLiveNum = liveLogService.getLiveNum(SecurityUtils.getShopUser().getShopId(), LiveInterfaceType.DELETE_PROD);
        liveNum.setDeleteShopNum(deleteLiveNum.getShopNum());
        liveNum.setDeleteTotalNum(deleteLiveNum.getTotalNum());
        return ResponseEntity.ok(liveNum);
    }

    /**
     * 查询商家今日剩余可用修改直播商品次数
     */
    @GetMapping("/getUpdateProdNum" )
    public ResponseEntity<LiveUsableNumParam> getUpdateProdNum() {
        return ResponseEntity.ok(liveLogService.getLiveNum(SecurityUtils.getShopUser().getShopId(), LiveInterfaceType.UPDATE_PROD));
    }

    @GetMapping("/getMediaId/{liveProdStoreId}")
    public ResponseEntity<String> getMediaId(@PathVariable("liveProdStoreId") Long liveProdStoreId) {
        String str = "http://img-test.gz-yami.com/2020/07/45d3631e97d8438d80f9db1369595b8c.jpg";
        LiveProdStore liveProdStore = liveProdStoreService.getById(liveProdStoreId);
        return ResponseEntity.ok(wxImageUtil.wxImageUpload(liveProdStore.getCoverPic()));
    }

}
